package com.example.library.base;

import static com.orhanobut.logger.BuildConfig.DEBUG;

import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.example.library.R;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class MBaseActivity extends AppCompatActivity {
    //权限申请request code
    private final int PERMISSIONS_REQUEST_CODE = 0x1000;
    private PermissionCallback mCallback;
    private Map<String, Boolean> mPermissions;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (DEBUG) {
            Logger.i("LIFE:%s onStart", getClass());
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (DEBUG) {
            Logger.i("LIFE:%s onResume", getClass());
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (DEBUG) {
            Logger.i("LIFE:%s onPause", getClass());
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (DEBUG) {
            Logger.i("LIFE:%s onStop", getClass());
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (DEBUG) {
            Logger.i("LIFE:%s onRestart", getClass());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (DEBUG) {
            Logger.i("LIFE:%s onDestroy", getClass());
        }
    }

    /**
     * 权限回调
     */
    public interface PermissionCallback {
        /**
         * 0 全部通过,-1 有未通过的
         */
        void onGranted(int type, List<String> permissionsGranted);

        /**
         * 全部拒绝. 返回false表示不拦截, true进行拦截. 拦截后不进行自定义提示
         *
         * @return
         */
        default boolean onReject() {
            return false;
        }
    }

    /**
     * @param permissions 包括权限字符串和是否是必要的权限
     *                    如:permission.put(Manifest.permission.READ_EXTERNAL_STORAGE,true)表示读取SD卡权限是必须赋予的,如果拒绝则退出当前Activity
     *                    如果是false则不退出继续使用
     * @param callback    授权成功回调
     */
    public void checkAndRequestPermissions(Map<String, Boolean> permissions,
                                           PermissionCallback callback) {
        Set<String> permissionNames = permissions.keySet();
        ArrayList<String> notGrantedPermissions = new ArrayList<>();
        for (String permissionName : permissionNames) {
            if (ActivityCompat.checkSelfPermission(this, permissionName) !=
                    PackageManager.PERMISSION_GRANTED) {
                notGrantedPermissions.add(permissionName);
            }
        }
        if (notGrantedPermissions.size() > 0) {
            mCallback = callback;
            mPermissions = permissions;
            ActivityCompat.requestPermissions(this,
                    notGrantedPermissions.toArray(new String[]{}),
                    PERMISSIONS_REQUEST_CODE);
        } else {
            callback.onGranted(0, Arrays.asList(permissionNames.toArray(new String[]{})));
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSIONS_REQUEST_CODE) {
            //            mPermissions.get(permission);

            List<String> permissionsGranted = new LinkedList<>();//授予的权限
            List<String> permissionsNotGranted = new LinkedList<>();//未授予的权限
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                    permissionsNotGranted.add(permissions[i]);
                } else {
                    permissionsGranted.add(permissions[i]);
                }
            }
            if (permissionsNotGranted.size() == 0) {
                //全部通过
                if (mCallback != null) {
                    mCallback.onGranted(0, permissionsGranted);
                }
            } else {
                //未全部通过
                for (String s : permissionsNotGranted) {
                    if (mPermissions.get(s)) {
                        if (!mCallback.onReject()) {
                            showMissingPermissionDialog(permissionsGranted, permissionsNotGranted);
                        }
                        return;
                    }
                }
                mCallback.onGranted(-1, permissionsNotGranted);
            }
        }
    }

    // 显示缺失权限提示
    private void showMissingPermissionDialog(List<String> permissionsGranted,
                                             List<String> permissionsNotGranted) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.my_help);
        builder.setMessage(R.string.my_prompt_permission_);

        // 拒绝, 退出应用
        builder.setNegativeButton(R.string.my_cancel, (dialog, which) -> {
            if (mPermissions != null) {
                for (String s : permissionsNotGranted) {
                    if (mPermissions.get(s)) {
                        dialog.dismiss();
                        return;
                    }
                }
            }
            if (mCallback != null) {
                mCallback.onGranted(-1, permissionsGranted);
            }
        });

        builder.setPositiveButton(R.string.my_settings, (dialog, which) -> {
            startAppSettings();
        });

        builder.show();
    }

    // 启动应用的设置
    private void startAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }
}
